<!--
*@Author: zt
*@Description: 请假审核
*@Params: pType  1 考勤申请     2 考勤审核
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100">
    <u-table-header class="s-bg-white">
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        @formChange="getSearch(1)"
        class="f-w-auto">
        <a-col>
          <u-button-space v-if="!isFast">
            <u-icon-button
              itype="search"
              @click="getSearch(1)">
              查询
            </u-icon-button>
            <u-icon-button
              itype="record"
              @click="showFlow = true">
              流程记录
            </u-icon-button>
          </u-button-space>
        </a-col>
        <a-col
          flex="1"
          align="end">
          <u-button-space>
            <template v-if="route.params.pType == 1 || isFast">
              <u-icon-button
                itype="record"
                v-if="isFast"
                @click="showFlow = true">
                流程记录
              </u-icon-button>
              <u-icon-button
                itype="report"
                @click="auditAbout('1')">
                上报
              </u-icon-button>
              <u-icon-button
                itype="recall"
                @click="auditAbout('4')">
                取回
              </u-icon-button>
              <u-icon-button
                itype="delete"
                @click="deleteBtn()">
                删除
              </u-icon-button>
            </template>
            <template v-else-if="route.params.pType == 2">
              <u-icon-button
                itype="audit"
                v-if="showAuditBnt"
                @click="auditAbout('2')">
                审核
              </u-icon-button>
              <u-icon-button
                itype="recall"
                @click="auditAbout('4')"
                v-if="searchF.model.status == 3">
                取回
              </u-icon-button>
              <u-icon-button
                itype="close"
                v-if="showAuditBnt"
                @click="auditAbout('3')">
                退回
              </u-icon-button>
            </template>
          </u-button-space>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content style="position: relative; padding: 0 12px; overflow-y: auto">
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="tabLoading"
        v-model:pagination="pagenation"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @onDblclick="onDblclick"
        @change="getSearch()" />
    </u-table-content>
  </a-layout>

  <!-- 考勤编辑 -->
  <VacatEdit
    v-model:open="showEdit"
    :busiType="busiType"
    :keyid="keyid"
    :formDisabled="formDisabled"
    :isAudited="showAuditBnt"
    @success="getSearch(), (keyid = ''), (showEdit = false)"
    @close="keyid = ''"
    wrap-class-name="full-modal" />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="leave_apply" />
</template>
<script lang="ts" setup>
import { formtTableEcho, formtTableEnum, formatStatus } from "@/util/format.ts";
import { isValue, nullC, numberC, confirmC } from "@/util/common";
import { computed, h, onMounted, reactive, ref, watch, onActivated, isRef } from "vue";
import { useLoginStore, useBaseStore } from "@/store";
import { storeToRefs } from "pinia";
import { useRoute } from "vue-router";
import { useTableScroll } from "@/hooks/useTable";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import { usePageTypeShow, useSearchShow } from "@/hooks/useAuditEl";
import { alertC, messageC } from "@/util/common";
import VacatEdit from "../myCheckIn/VacatEdit.vue";
import dayjs from "dayjs";
import * as myCheckInApi from "@/service/personnel/myCheckIn/index";

const props = defineProps<{
  isFast?: boolean; // 是否是快捷引用
}>();

const { userInfo } = storeToRefs(useLoginStore());
const { APP_STATUS } = storeToRefs(useBaseStore());

const applicanttypeType = ref([
  { name: "加班", id: 1 },
  { name: "请假", id: 2 },
  { name: "离驻地", id: 3 },
]);

const route = useRoute();

let searchF = reactive<any>({
  current: 1,
  size: 100,
  sort: "fkdeptid",
  order: "ascending",
  model: {
    keywords: "",
    status: null,
    applicanttype: null,
    pageStatus: "",
  },
});

// 曾经办，不显示审核和退回按钮
const showAuditBnt = ref<boolean>(useSearchShow(searchF.model, "3", { result: false, noResult: true }));

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 20,
  showTotal: (total) => `共 ${total} 条`,
});

const formItemProps: FormItemProps = {
  labelWidth: props.isFast == true ? 0 : "72px",
  wrapperCol: { span: 24 },
};
const searchEl: Array<_IFormEl> = reactive([
  {
    label: props.isFast ? "" : "考勤类型",
    key: "applicanttype",
    element: "select",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: {
      placeholder: "考勤类型",
      options: applicanttypeType.value,
      fieldNames: { label: "name", value: "id" },
    },
  },
  {
    label: props.isFast ? "" : "审核状态",
    key: "status",
    element: "select",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: {
      allowClear: route.params.pType == "2" ? false : true,
      placeholder: "审核状态",
      options:
        route.params.pType == "2"
          ? [
              { label: "待审核", value: "2" },
              { label: "曾经办", value: "3" },
            ]
          : APP_STATUS.value,
    },
  },
]);

const tabLoading = ref(false);
const total = ref(0);
const tabData = ref([]);
const tabSelData = ref([]);
let columns = ref([
  {
    dataIndex: "index",
    title: "序号",
    width: 60,
    align: "center",
    customRender: ({ text, record, index }) => {
      return index + 1;
    },
  },
  {
    title: "部门",
    width: 140,
    align: "center",
    dataIndex: "fkdeptname",
    sortable: "custom",
  },
  {
    title: "申请人",
    width: 120,
    align: "center",
    dataIndex: "fkapplicant",
    sortable: "custom",
  },
  {
    title: "类型",
    width: 120,
    align: "center",
    dataIndex: "applicanttype",
    sortable: "custom",
    customRender: ({ text }) => {
      let item = applicanttypeType.value.find((i) => i.id == text);
      return item ? item["name"] : "";
    },
  },
  {
    title: "填报时间",
    width: 120,
    align: "center",
    dataIndex: "createtime",
    sortable: "custom",
    customRender: ({ text, record }) => {
      return (text || "").split(" ")[0];
    },
  },
  {
    title: "开始时间",
    width: 120,
    align: "center",
    dataIndex: "startdate",
    sortable: "custom",
    customRender: ({ text, record }) => {
      let formatStr = record.applicanttype == "1" ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD";
      return text ? dayjs(text).format(formatStr) : "";
    },
  },
  {
    title: "结束时间",
    width: 120,
    align: "center",
    dataIndex: "endstart",
    sortable: "custom",
    customRender: ({ text, record }) => {
      let formatStr = record.applicanttype == "1" ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD";
      return text ? dayjs(text).format(formatStr) : "";
    },
  },
  {
    title: "事由",
    width: 100,
    align: "center",
    dataIndex: "reason",
    // fixed: "right",
  },
  {
    title: "当前审核人",
    width: 100,
    align: "center",
    dataIndex: "reauditusername",
    fixed: "right",
  },
  {
    title: "审核状态",
    width: 100,
    align: "center",
    dataIndex: "status",
    customRender: ({ text, record }) => formatStatus(text, record),
    fixed: "right",
  },
]);

const initPage = () => {
  searchF.model.pageStatus = route.params.pType ? route.params.pType : "1";
  const pTypes = { 1: 1, 2: "2" };
  searchF.model.status = nullC(pTypes[searchF.model.pageStatus]);
  if (props.isFast == true) {
    searchF.model.status = '';
  }
  getSearch();
};

// 获取列表数据
const getSearch = async (current?: number) => {
  let tform = JSON.parse(JSON.stringify(searchF));
  if (current == 1) {
    pagenation.current = 1;
  }
  tform.current = pagenation.current;
  tform.size = pagenation.pageSize;
  tabLoading.value = true;
  try {
    const res = await myCheckInApi.page({ ...tform });
    if (res.code == 0) {
      tabData.value = res.data["records"] || [];
      pagenation.total = numberC(res.data.total);
    }
  } catch (error) {}
  tabLoading.value = false;
};

// 上报、审核、退回
const auditAbout = async (type: string | number) => {
  const auditParams: IAuditParams = {
    type: "leave_apply",
    selDatas: tabSelData.value,
  };

  tabLoading.value = true;
  try {
    const res = await useAuditAbout(type, auditParams);
    if (res) {
      getSearch(1);
    }
  } catch (error) {}
  tabLoading.value = false;
};

// 设置参数
const initSetParasm = () => {
  if (sessionStorage.getItem("stay_do_params")) {
    searchF.model = {
      ...searchF.model,
      ...JSON.parse(sessionStorage.getItem("stay_do_params") || "{}"),
    };
    getSearch(1);
  }
};

// 打开编辑
const showFlow = ref(false);
let showEdit = ref<boolean>(false);
let busiType = ref<string>("");
let keyid = ref("");
let formDisabled = ref(false);
//填报列表数据展示
const onDblclick = (record) => {
  keyid.value = record["keyid"];
  busiType.value = record["applicanttype"];
  if (record["status"] == 3 || record["status"] == 2) {
    formDisabled.value = true;
  } else {
    formDisabled.value = false;
  }
  showEdit.value = true;
};

// 删除功能
const deleteBtn = async (record?: any) => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择要删除的数据！");
    return;
  }

  let noDel = tabSelData.value.some((i) => ["2", "3"].includes(i["status"] + ""));
  if (noDel) {
    messageC("审核中或审核完成的数据不能删除!");
    return;
  }

  let ids = tabSelData.value.map((item) => item.keyid);
  if (record) {
    ids = [record.keyid];
  }
  tabLoading.value = true;
  try {
    await alertC("确认删除？", 'confirm');
    const res = await myCheckInApi.del({ ids: ids.join(",") });
    if (res.code == 0) {
      getSearch();
      alertC(res.msg, "success");
    } else {
      alertC(res.msg, "warning");
    }
  } catch (error) {};
  tabLoading.value = false;
};

onMounted(async () => {
  if (props.isFast == true) {
    searchF.model.pageStatus = "1";
    return;
  }
  initPage();
});

onActivated(() => {
  if (props.isFast == true) {
    return;
  }
  initPage();
});

defineExpose({
  getSearch,
});

watch(
  () => route.path,
  (nval, oval) => {
    if (nval == "/TransitIndex/MyCheckIn") {
      initSetParasm();
    }
  },
  { deep: true }
);
</script>
<style lang="scss">
.u-jhk-serch-datepicker {
  .el-range-separator {
    padding: 0;
    width: unset;
  }
}
</style>
